package com.lagou.proxy;

import com.lagou.service.AccountService;
import com.lagou.service.impl.AccountServiceImpl;
import com.lagou.utils.TransManage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @program: spring_transfer
 * @description:
 * @author: Mr.Wang
 * @create: 2020-12-16 15:38
 **/
@Component
public class CGLIBProxyFactory {

	@Autowired
	private AccountService accountService;

	@Autowired
	private TransManage transManage;

	public AccountService getAccountServiceProxy(){
		AccountService accountServiceproxy = (AccountService)Enhancer.create(accountService.getClass(), new MethodInterceptor() {
			@Override
			public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
				Object invoke = null;
				if ("transfer".equals(method.getName())) {
					try {
						transManage.beginTransaction();
						invoke = method.invoke(accountService, objects);
						transManage.commit();
					} catch (Exception e) {
						e.printStackTrace();
						transManage.rollback();
					} finally {
						transManage.close();
					}
				}
				return o;
			}
		});
		return accountServiceproxy;
	}
}
